﻿'TODO: Document Freeze Control
Public Class FreezeControl
    Implements IDisposable

    Private _disposedValue As Boolean = False        ' To detect redundant calls

    Private _FrozenControl As Control
    Private _pbImage As PictureBox
    Private _ParentForm As Form = Nothing

    Public Sub New(ByVal Ctl As Control)
        _FrozenControl = Ctl
        _ParentForm = Ctl.FindForm()
    End Sub
    Public Sub New(ByVal Ctl As Control, ByVal IsFrozen As Boolean)
        _FrozenControl = Ctl
        _ParentForm = Ctl.FindForm()
        If IsFrozen Then
            FreezeControl()
        End If
    End Sub

    Public Sub FreezeControl()
        ThawControl() 'First unfreeze control in case it has been previously frozen

        'Get a static bitmap of current control and assign to _pbImage
        Dim FormG As Graphics = _ParentForm.CreateGraphics()

        Dim CtlScrLocation As Point
        Dim CtlFrmLocation As Point
        If _FrozenControl Is _ParentForm Then
            CtlScrLocation = _ParentForm.PointToScreen(_ParentForm.ClientRectangle.Location)
            CtlFrmLocation = _ParentForm.ClientRectangle.Location
        Else
            CtlScrLocation = _FrozenControl.Parent.PointToScreen(_FrozenControl.Location)
            CtlFrmLocation = _ParentForm.PointToClient(CtlScrLocation)
        End If

        Dim CtlSize As Size = _FrozenControl.ClientSize

        _pbImage = New PictureBox()
        _pbImage.Size = CtlSize
        _pbImage.SizeMode = PictureBoxSizeMode.AutoSize
        _pbImage.Image = New Bitmap(CtlSize.Width, CtlSize.Height, FormG)

        Dim ImageG As Graphics = Graphics.FromImage(_pbImage.Image)
        ImageG.CopyFromScreen(New Point(CtlScrLocation.X, CtlScrLocation.Y), New Point(0, 0), CtlSize)

        _ParentForm.Controls.Add(_pbImage)
        _pbImage.Location = CtlFrmLocation
        _pbImage.BringToFront()

        ImageG.Dispose()
        FormG.Dispose()
    End Sub

    Public Sub ThawControl()
        If _ParentForm.Contains(_pbImage) Then
            _ParentForm.Controls.Remove(_pbImage)
            _pbImage.Dispose()
            _pbImage = Nothing
        End If
    End Sub

    ' IDisposable
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not _disposedValue Then
            If disposing Then
                ThawControl()
            End If
        End If
        _disposedValue = True
    End Sub

#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class

